<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>

            <!-- 警告区域 -->
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning" :closable="false" show-icon>
            </el-alert>

            <!-- 选择商品分类区域 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>

                    <!-- 选择商品分类的级联选择框 -->
                    <el-cascader
                        clearable
                        v-model="selectKeys"
                        :options="cateList"
                        :props="cascaderProps"
                        @change="handleChange">
                    </el-cascader>
                    <el-tabs v-model="activeName" @tab-click="handleClick">


                        <!-- 添加动态参数面板1 -->
                        <el-tab-pane label="动态参数" name="many">

                            <!-- 添加参数按钮 -->
                            <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true" class="button">添加参数</el-button>

                            <!-- 动表格 -->
                            <el-table :data="manyTableData" expand border stripe>

                                <!-- 展开行 -->
                                <el-table-column type="expand">
                                    <template v-slot="scope">
                                        <el-tag closable class="tag" v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                                        <el-input
                                            class="input-new-tag"
                                            v-if="scope.row.inputVisible"
                                            v-model="scope.row.inputValue"
                                            ref="saveTagInput"
                                            size="small"
                                            @keyup.enter.native="handleInputConfirm(scope.row)"
                                            @blur="handleInputConfirm(scope.row)"
                                        >
                                        </el-input>
                                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                    </template>

                                </el-table-column>

                                <!-- 索引列 -->
                                <el-table-column type="index"></el-table-column>
                                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                                <el-table-column label="操作">
                                    <template v-slot="scope">

                                        <!-- 修改按钮 -->
                                        <el-button type="primary" icon="el-icon-edit" @click="showEditdialog(scope.row.attr_id)" size="mini">修改</el-button>

                                        <!-- 删除按钮 -->
                                        <el-button type="danger" icon="el-icon-delete" @click="shanChu(scope.row.attr_id)" size="mini">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            
                        </el-tab-pane>


                        <!-- 添加静态属性面板2 -->
                        <el-tab-pane label="静态属性" name="only">

                            <!-- 添加参数按钮 -->
                            <el-button type="primary" :disabled="isBtnDisabled"  @click="addDialogVisible = true" class="button">添加属性</el-button>

                            <!-- 静表格 -->
                            <el-table :data="onlyTableData" expand border stripe>

                                <!-- 展开行 -->
                                <el-table-column type="expand">
                                    <template v-slot="scope">
                                        <el-tag closable class="tag" v-for="(item,i) in scope.row.attr_vals" :key="i"  @close="handClose(i,scope.row)">{{item}}</el-tag>
                                        <el-input
                                            class="input-new-tag"
                                            v-if="scope.row.inputVisible"
                                            v-model="scope.row.inputValue"
                                            ref="saveTagInput"
                                            size="small"
                                            @keyup.enter.native="handleInputConfirm(scope.row)"
                                            @blur="handleInputConfirm(scope.row)"
                                        >
                                        </el-input>
                                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                    </template>
                                </el-table-column>

                                <!-- 索引列 -->
                                <el-table-column type="index"></el-table-column>
                                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                                <el-table-column label="操作">
                                    <template v-slot="scope">

                                        <!-- 修改按钮 -->
                                        <el-button type="primary" icon="el-icon-edit" @click="showEditdialog(scope.row.attr_id)" size="mini">修改</el-button>

                                        <!-- 删除按钮 -->
                                        <el-button type="danger" icon="el-icon-delete" @click="shanChu(scope.row.attr_id)" size="mini">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
            </el-row>
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog
            @close="addClose()"
            :title="'添加'+shuXing"
            :visible.sync="addDialogVisible"
            width="50%">
            <span>{{shuXing}}：</span>

            <!-- 添加参数对话框 -->
            <el-form :model="addRuleForm" :rules="Catrules" ref="ruleFormRef" label-width="100px">
                <el-form-item :label="shuXing" prop="attr_name">
                    <el-input v-model="addRuleForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addCan()">确 定</el-button>
            </span>
        </el-dialog>


        <!-- 编辑参数对话框 -->
        <el-dialog
            @close="aditClose()"
            :title="'添加'+shuXing"
            :visible.sync="aditDialogVisible"
            width="50%">
            <span>{{shuXing}}：</span>

            <!-- 编辑参数对话框 -->
            <el-form :model="aditRuleForm" :rules="Editrules" ref="aditRuleFormRef" label-width="100px">
                <el-form-item :label="shuXing" prop="attr_name">
                    <el-input v-model="aditRuleForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="aditDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="xiuGai()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {

            //商品数据列表
            cateList:[],

            //级联选择框的配置对象
            cascaderProps:{
                expandTrigger: 'hover',

                //当前选中的值
                value:'cat_id',
                label:"cat_name",
                children:'children'
            },
            //和选中的value的值双向绑定
            selectKeys:[],
            activeName:'many',

            //动
            manyTableData:[],

            //静
            onlyTableData:[],
            addDialogVisible:false,
            input:'',

            //添加参数的表单数据对象
            addRuleForm:{},

            //参数规则列表
            Catrules:{
                attr_name:[
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ]
            },
            aditDialogVisible:false,
            aditRuleForm:{},
            Editrules:{
                attr_name:[
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ]
            }


        }
    },
    methods: {

        //商品数据列表·
        async getCatList(){
            const { data } = await this.axios.get('categories')
            this.cateList= data.data
           // console.log(data)
        },

        //级联选择框中选项发生变化触发
        handleChange(){
            this.getParamsData()


        },

        //获取参数列表的数据

        async getParamsData(){
            if(this.selectKeys.length !== 3){
                this.selectKeys=[]
                this.manyTableData = []
                this.onlyTableData = []
                return
            }
            //console.log(this.selectKeys)
            const { data } = await this.axios.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
           // console.log(data)

            data.data.forEach(item=>{
                item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
                item.inputVisible = false
                item.inputValue = ''
            })

            //console.log(data.data)

            if(this.activeName ==='many'){
                this.manyTableData = data.data
            }else{
                 this.onlyTableData = data.data
            }
        },
        //切换标签页时触发
        handleClick(){
            this.getParamsData()
        },

        //添加参数
        addCan(){
            this.$refs.ruleFormRef.validate(async valid=>{
                if(!valid){
                    return
                }
                const { data } = await this.axios.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addRuleForm.attr_name,
                    attr_sel:this.activeName
                })
               // console.log(data)
                this.getParamsData()
            })


            this.addDialogVisible = false
        },

        //监听对话框关闭事件
        addClose(){
            this.$refs.ruleFormRef.resetFields()
        },

        //清空表单
        aditClose(){
            this.$refs.aditRuleFormRef.resetFields()
        },

        //点击按钮，修改展示的对话框
        async showEditdialog(attr_id){

            const { data } = await this.axios.get(`categories/${this.cateId}/attributes/${attr_id}`,{params:{attr_sel:this.activeName}})

           this.aditRuleForm = data.data

            //console.log(data)

            
            this.aditDialogVisible = true
            this.$message.success('修改分类成功！')
            this.getParamsData()
        },

        //对话框修改提交
        xiuGai(){

            
            this.$refs.aditRuleFormRef.validate( async valid=>{

                if(!valid){
                    return
                }
                
                const { data } = await this.axios.put(`categories/${this.cateId}/attributes/${this.aditRuleForm.attr_id}`,{
                    attr_name:this.aditRuleForm.attr_name,attr_sel:this.activeName
                })
                //console.log(data)
                this.getCatList()
            })
            

            this.aditDialogVisible = false
        },
        async shanChu(id){
             const data1 = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            if(data1 == 'confirm'){
                const { data } = await this.axios.delete(`categories/${this.cateId}/attributes/${id}`)
               // console.log(data)
                this.$message.success('删除分类成功！')
            }
            this.getParamsData()
        },

        //文本框失去焦点或摁下enter键
        async handleInputConfirm(row){
            
            if(row.inputValue.trim().length === 0){
                row.inputValue = ''
                row.inputVisible = false
                return
            }

            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ''
            row.inputVisible = false
            this.saveAttrVals(row)
            
            
        },
        showInput(row){

            row.inputVisible = true

            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
       async saveAttrVals(row){
            const { data } = await this.axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_vals:row.attr_vals.join(','),
                attr_sel:row.attr_sel
            })
            this.$message.success('修改参数项成功！')
            console.log(data)
        },
        handClose(i,row){
            row.attr_vals.splice(i,1)
            this.saveAttrVals(row)
        }

    },
    created() {
        this.getCatList()
    },
    computed: {
        //如果按钮需要被禁用返回true
        isBtnDisabled(){
            if(this.selectKeys.length !== 3){
                return true
            }else{
                return false
            }
        },
        cateId(){
            if(this.selectKeys.length == 3){
                return this.selectKeys[2]
            }else{
                return null;
            }
        },
        shuXing(){
            if(this.activeName == 'many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }
    }
    
    
}
</script>
<style lang="less" scoped>
    .cat_opt{
        margin: 15px 0;
    }
    .button{
        margin-bottom: 15px;
    }
    .tag{
        margin-right: 10px;
    }
    .input-new-tag{
        width: 120px;
    }
</style>